<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>React16.3新的生命周期详解 | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="React,生命周期,">
  

  <meta name="description" content="一、React v16.0前的生命周期 1.1 第一个是组件初始化(initialization)阶段 也就是以下代码中类的构造方法( constructor() ),Test类继承了react Component这个基类，也就继承这个react的基类，才能有render(),生命周期等方法可以使用，这也说明为什么函数组件不能使用这些方法的原因  super(props)用来调用基类的构造方法(">
<meta name="keywords" content="React,生命周期">
<meta property="og:type" content="article">
<meta property="og:title" content="React16.3新的生命周期详解">
<meta property="og:url" content="http://blog.poetries.top/2018/11/18/react-lifecircle/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="一、React v16.0前的生命周期 1.1 第一个是组件初始化(initialization)阶段 也就是以下代码中类的构造方法( constructor() ),Test类继承了react Component这个基类，也就继承这个react的基类，才能有render(),生命周期等方法可以使用，这也说明为什么函数组件不能使用这些方法的原因  super(props)用来调用基类的构造方法(">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/417.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/418.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/419.png">
<meta property="og:updated_time" content="2020-08-15T04:25:31.930Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="React16.3新的生命周期详解">
<meta name="twitter:description" content="一、React v16.0前的生命周期 1.1 第一个是组件初始化(initialization)阶段 也就是以下代码中类的构造方法( constructor() ),Test类继承了react Component这个基类，也就继承这个react的基类，才能有render(),生命周期等方法可以使用，这也说明为什么函数组件不能使用这些方法的原因  super(props)用来调用基类的构造方法(">
<meta name="twitter:image" content="https://poetries1.gitee.io/img-repo/2019/10/417.png">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一、React-v16-0前的生命周期"><span class="toc-text">一、React v16.0前的生命周期</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-第一个是组件初始化-initialization-阶段"><span class="toc-text">1.1 第一个是组件初始化(initialization)阶段</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-第二个是组件的挂载-Mounting-阶段"><span class="toc-text">1.2 第二个是组件的挂载(Mounting)阶段</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-2-1-componentWillMount"><span class="toc-text">1.2.1 componentWillMount</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-2-2-render"><span class="toc-text">1.2.2 render</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-2-3-componentDidMount"><span class="toc-text">1.2.3 componentDidMount</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-3-第三个是组件的更新-update-阶段"><span class="toc-text">1.3 第三个是组件的更新(update)阶段</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-3-1-造成组件更新有两类（三种）情况"><span class="toc-text">1.3.1 造成组件更新有两类（三种）情况</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-3-2-componentWillReceiveProps-nextProps"><span class="toc-text">1.3.2 componentWillReceiveProps(nextProps)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-3-3-shouldComponentUpdate-nextProps-nextState"><span class="toc-text">1.3.3 shouldComponentUpdate(nextProps, nextState)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-3-4-componentWillUpdate-nextProps-nextState"><span class="toc-text">1.3.4 componentWillUpdate(nextProps, nextState)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-3-5-componentDidUpdate-prevProps-prevState"><span class="toc-text">1.3.5 componentDidUpdate(prevProps, prevState)</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-4-卸载阶段"><span class="toc-text">1.4 卸载阶段</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二、React-v16-4-的生命周期"><span class="toc-text">二、React v16.4 的生命周期</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-变更缘由"><span class="toc-text">2.1 变更缘由</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-引入了两个新的生命周期函数"><span class="toc-text">2.2 引入了两个新的生命周期函数</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#2-2-1-getDerivedStateFromProps"><span class="toc-text">2.2.1 getDerivedStateFromProps</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-2-2-getSnapshotBeforeUpdate"><span class="toc-text">2.2.2 getSnapshotBeforeUpdate</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#三、参考"><span class="toc-text">三、参考</span></a></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-react-lifecircle" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">React16.3新的生命周期详解</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2018.11.18</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Front-End/">Front-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 2.1k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 8分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <h2 id="一、React-v16-0前的生命周期"><a href="#一、React-v16-0前的生命周期" class="headerlink" title="一、React v16.0前的生命周期"></a>一、React v16.0前的生命周期</h2><p><img src="https://poetries1.gitee.io/img-repo/2019/10/417.png" alt></p>
<h3 id="1-1-第一个是组件初始化-initialization-阶段"><a href="#1-1-第一个是组件初始化-initialization-阶段" class="headerlink" title="1.1 第一个是组件初始化(initialization)阶段"></a>1.1 第一个是组件初始化(initialization)阶段</h3><blockquote>
<p>也就是以下代码中类的构造方法( <code>constructor()</code> ),Test类继承了react <code>Component</code>这个基类，也就继承这个<code>react</code>的基类，才能有<code>render()</code>,生命周期等方法可以使用，这也说明为什么函数组件不能使用这些方法的原因</p>
</blockquote>
<p><code>super(props)</code>用来调用基类的构造方法( <code>constructor()</code> ), 也将父组件的props注入给子组件，功子组件读取(组件中<code>props</code>只读不可变，<code>state</code>可变)而<code>constructor()</code>用来做一些组件的初始化工作，如定义<code>this.state</code>的初始内容</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> React, &#123; Component &#125; <span class="keyword">from</span> <span class="string">'react'</span>;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Test</span> <span class="keyword">extends</span> <span class="title">Component</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>(props) &#123;</span><br><span class="line">    <span class="keyword">super</span>(props);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="1-2-第二个是组件的挂载-Mounting-阶段"><a href="#1-2-第二个是组件的挂载-Mounting-阶段" class="headerlink" title="1.2 第二个是组件的挂载(Mounting)阶段"></a>1.2 第二个是组件的挂载(Mounting)阶段</h3><p><strong>此阶段分为componentWillReceiveProps，shouldComponentUpdate，componentWillUpdate，render，componentDidUpdate</strong></p>
<h4 id="1-2-1-componentWillMount"><a href="#1-2-1-componentWillMount" class="headerlink" title="1.2.1 componentWillMount"></a>1.2.1 componentWillMount</h4><blockquote>
<p>在组件挂载到DOM前调用，且只会被调用一次，在这边调用<code>this.setState</code>不会引起组件重新渲染，也可以把写在这边的内容提前到<code>constructor()</code>中，所以项目中很少用</p>
</blockquote>
<h4 id="1-2-2-render"><a href="#1-2-2-render" class="headerlink" title="1.2.2 render"></a>1.2.2 render</h4><blockquote>
<p>根据组件的<code>props</code>和<code>state</code>（无两者的重传递和重赋值，论值是否有变化，都可以引起组件重新<code>render</code>） ，<code>return</code> 一个<code>React</code>元素（描述组件，即<code>UI</code>），不负责组件实际渲染工作，之后由<code>React</code>自身根据此元素去渲染出页面<code>DOM</code>。<code>render</code>是纯函数（<code>Pure function</code>：函数的返回结果只依赖于它的参数；函数执行过程里面没有副作用），不能在里面执行<code>this.setState</code>，会有改变组件状态的副作用</p>
</blockquote>
<h4 id="1-2-3-componentDidMount"><a href="#1-2-3-componentDidMount" class="headerlink" title="1.2.3 componentDidMount"></a>1.2.3 componentDidMount</h4><blockquote>
<p>组件挂载到<code>DOM</code>后调用，且只会被调用一次</p>
</blockquote>
<h3 id="1-3-第三个是组件的更新-update-阶段"><a href="#1-3-第三个是组件的更新-update-阶段" class="headerlink" title="1.3 第三个是组件的更新(update)阶段"></a>1.3 第三个是组件的更新(update)阶段</h3><blockquote>
<p><code>setState</code>引起的<code>state</code>更新或父组件重新<code>render</code>引起的<code>props</code>更新，更新后的<code>state</code>和<code>props</code>相对之前无论是否有变化，都将引起子组件的重新<code>render</code></p>
</blockquote>
<h4 id="1-3-1-造成组件更新有两类（三种）情况"><a href="#1-3-1-造成组件更新有两类（三种）情况" class="headerlink" title="1.3.1 造成组件更新有两类（三种）情况"></a>1.3.1 造成组件更新有两类（三种）情况</h4><p><strong>1. 父组件重新render</strong></p>
<blockquote>
<p>父组件重新<code>render</code>引起子组件重新<code>render</code>的情况有两种</p>
</blockquote>
<ul>
<li>a. 直接使用,每当父组件重新<code>render</code>导致的重传<code>props</code>，子组件将直接跟着重新渲染，无论<code>props</code>是否有变化。可通过<code>shouldComponentUpdate</code>方法优化</li>
</ul>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Child</span> <span class="keyword">extends</span> <span class="title">Component</span> </span>&#123;</span><br><span class="line">   shouldComponentUpdate(nextProps)&#123; <span class="comment">// 应该使用这个方法，否则无论props是否有变化都将会导致组件跟着重新渲染</span></span><br><span class="line">        <span class="keyword">if</span>(nextProps.someThings === <span class="keyword">this</span>.props.someThings)&#123;</span><br><span class="line">          <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    render() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span>&#123;this.props.someThings&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>b.在<code>componentWillReceiveProps</code>方法中，将<code>props</code>转换成自己的<code>state</code></li>
</ul>
<figure class="highlight jsx"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Child</span> <span class="keyword">extends</span> <span class="title">Component</span> </span>&#123;</span><br><span class="line">    <span class="keyword">constructor</span>(props) &#123;</span><br><span class="line">        <span class="keyword">super</span>(props);</span><br><span class="line">        <span class="keyword">this</span>.state = &#123;</span><br><span class="line">            someThings: props.someThings</span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;</span><br><span class="line">    componentWillReceiveProps(nextProps) &#123; <span class="comment">// 父组件重传props时就会调用这个方法</span></span><br><span class="line">        <span class="keyword">this</span>.setState(&#123;<span class="attr">someThings</span>: nextProps.someThings&#125;);</span><br><span class="line">    &#125;</span><br><span class="line">    render() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span>&#123;this.state.someThings&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>在该函数(<code>componentWillReceiveProps</code>)中调用 <code>this.setState()</code> 将不会引起第二次渲染</p>
</blockquote>
<p>是因为<code>componentWillReceiveProps</code>中判断<code>props</code>是否变化了，若变化了，<code>this.setState</code>将引起<code>state</code>变化，从而引起<code>render</code>，此时就没必要再做第二次因重传<code>props</code>引起的<code>render</code>了，不然重复做一样的渲染了</p>
<p><strong>2. 组件本身调用setState，无论state有没有变化。可通过shouldComponentUpdate方法优化</strong></p>
<figure class="highlight jsx"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Child</span> <span class="keyword">extends</span> <span class="title">Component</span> </span>&#123;</span><br><span class="line">   <span class="keyword">constructor</span>(props) &#123;</span><br><span class="line">        <span class="keyword">super</span>(props);</span><br><span class="line">        <span class="keyword">this</span>.state = &#123;</span><br><span class="line">          someThings:<span class="number">1</span></span><br><span class="line">        &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   shouldComponentUpdate(nextStates)&#123; <span class="comment">// 应该使用这个方法，否则无论state是否有变化都将会导致组件重新渲染</span></span><br><span class="line">        <span class="keyword">if</span>(nextStates.someThings === <span class="keyword">this</span>.state.someThings)&#123;</span><br><span class="line">          <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">   handleClick = <span class="function"><span class="params">()</span> =&gt;</span> &#123; <span class="comment">// 虽然调用了setState ，但state并无变化</span></span><br><span class="line">        <span class="keyword">const</span> preSomeThings = <span class="keyword">this</span>.state.someThings</span><br><span class="line">         <span class="keyword">this</span>.setState(&#123;</span><br><span class="line">            someThings: preSomeThings</span><br><span class="line">         &#125;)</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">    render() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">div</span> <span class="attr">onClick</span> = <span class="string">&#123;this.handleClick&#125;</span>&gt;</span>&#123;this.state.someThings&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="1-3-2-componentWillReceiveProps-nextProps"><a href="#1-3-2-componentWillReceiveProps-nextProps" class="headerlink" title="1.3.2 componentWillReceiveProps(nextProps)"></a>1.3.2 componentWillReceiveProps(nextProps)</h4><blockquote>
<p>此方法只调用于<code>props</code>引起的组件更新过程中，参数<code>nextProps</code>是父组件传给当前组件的新<code>props</code>。但父组件<code>render</code>方法的调用不能保证重传给当前组件的<code>props</code>是有变化的，所以在此方法中根据<code>nextProps</code>和<code>this.props</code>来查明重传的<code>props</code>是否改变，以及如果改变了要执行啥，比如根据新的<code>props</code>调用<code>this.setState</code>出发当前组件的重新<code>render</code></p>
</blockquote>
<h4 id="1-3-3-shouldComponentUpdate-nextProps-nextState"><a href="#1-3-3-shouldComponentUpdate-nextProps-nextState" class="headerlink" title="1.3.3 shouldComponentUpdate(nextProps, nextState)"></a>1.3.3 shouldComponentUpdate(nextProps, nextState)</h4><blockquote>
<p>此方法通过比较<code>nextProps</code>，<code>nextState</code>及当前组件的<code>this.props</code>，<code>this.state</code>，返回<code>true</code>时当前组件将继续执行更新过程，返回<code>false</code>则当前组件更新停止，以此可用来减少组件的不必要渲染，优化组件性能。</p>
</blockquote>
<p>ps：这边也可以看出，就算<code>componentWillReceiveProps()</code>中执行了<code>this.setState</code>，更新了<code>state</code>，但在<code>render</code>前（如<code>shouldComponentUpdate</code>，<code>componentWillUpdate</code>），<code>this.state</code>依然指向更新前的<code>state</code>，不然<code>nextState</code>及当前组件的<code>this.state</code>的对比就一直是<code>true</code>了</p>
<h4 id="1-3-4-componentWillUpdate-nextProps-nextState"><a href="#1-3-4-componentWillUpdate-nextProps-nextState" class="headerlink" title="1.3.4 componentWillUpdate(nextProps, nextState)"></a>1.3.4 componentWillUpdate(nextProps, nextState)</h4><blockquote>
<p>此方法在调用<code>render</code>方法前执行，在这边可执行一些组件更新发生前的工作，一般较少用</p>
</blockquote>
<h4 id="1-3-5-componentDidUpdate-prevProps-prevState"><a href="#1-3-5-componentDidUpdate-prevProps-prevState" class="headerlink" title="1.3.5 componentDidUpdate(prevProps, prevState)"></a>1.3.5 componentDidUpdate(prevProps, prevState)</h4><blockquote>
<p>此方法在组件更新后被调用，可以操作组件更新的<code>DOM</code>，<code>prevProps</code>和<code>prevState</code>这两个参数指的是组件更新前的<code>props</code>和<code>state</code></p>
</blockquote>
<h3 id="1-4-卸载阶段"><a href="#1-4-卸载阶段" class="headerlink" title="1.4 卸载阶段"></a>1.4 卸载阶段</h3><blockquote>
<p>此阶段只有一个生命周期方法：<code>componentWillUnmount</code></p>
</blockquote>
<p>此方法在组件被卸载前调用，可以在这里执行一些清理工作，比如清楚组件中使用的定时器，清除<code>componentDidMount</code>中手动创建的<code>DOM</code>元素等，以避免引起内存泄漏</p>
<h2 id="二、React-v16-4-的生命周期"><a href="#二、React-v16-4-的生命周期" class="headerlink" title="二、React v16.4 的生命周期"></a>二、React v16.4 的生命周期</h2><p><strong>React v16.4 的生命周期图</strong></p>
<p><img src="https://poetries1.gitee.io/img-repo/2019/10/418.png" alt></p>
<h3 id="2-1-变更缘由"><a href="#2-1-变更缘由" class="headerlink" title="2.1 变更缘由"></a>2.1 变更缘由</h3><blockquote>
<p>原来（<code>React v16.0</code>前）的生命周期在<code>React v16</code>推出的<code>Fiber</code>之后就不合适了，因为如果要开启<code>async rendering</code>，在<code>render</code>函数之前的所有函数，都有可能被执行多次</p>
</blockquote>
<p><strong>原来（React v16.0前）的生命周期有哪些是在render前执行的呢？</strong></p>
<ul>
<li><code>componentWillMount</code></li>
<li><code>componentWillReceiveProps</code></li>
<li><code>shouldComponentUpdate</code></li>
<li><code>componentWillUpdate</code></li>
</ul>
<blockquote>
<p>如果开发者开了<code>async rendering</code>，而且又在以上这些<code>render</code>前执行的生命周期方法做<code>AJAX</code>请求的话，那<code>AJAX</code>将被无谓地多次调用。而且在<code>componentWillMount</code>里发起<code>AJAX</code>，不管多快得到结果也赶不上首次<code>render</code>，而且<code>componentWillMount</code>在服务器端渲染也会被调用到</p>
</blockquote>
<ul>
<li>所以除了<code>shouldComponentUpdate</code>，其他在<code>render</code>函数之前的所有函数（<code>componentWillMount</code>，<code>componentWillReceiveProps</code>，<code>componentWillUpdate</code>）都被<code>getDerivedStateFromProps</code>替代</li>
<li>也就是用一个静态函数<code>getDerivedStateFromProps</code>来取代被<code>deprecate</code>的几个生命周期函数，就是强制开发者在<code>render</code>之前只做无副作用的操作，而且能做的操作局限在根据<code>props</code>和<code>state</code>决定新的<code>state</code></li>
</ul>
<blockquote>
<p>React v16.0刚推出的时候，是增加了一个<code>componentDidCatch</code>生命周期函数，这只是一个增量式修改，完全不影响原有生命周期函数；但是，到了<code>React v16.3</code>，大改动来了，引入了两个新的生命周期函数</p>
</blockquote>
<h3 id="2-2-引入了两个新的生命周期函数"><a href="#2-2-引入了两个新的生命周期函数" class="headerlink" title="2.2 引入了两个新的生命周期函数"></a>2.2 引入了两个新的生命周期函数</h3><h4 id="2-2-1-getDerivedStateFromProps"><a href="#2-2-1-getDerivedStateFromProps" class="headerlink" title="2.2.1 getDerivedStateFromProps"></a>2.2.1 getDerivedStateFromProps</h4><blockquote>
<p><code>getDerivedStateFromProps</code>本来（React v16.3中）是只在创建和更新（由父组件引发部分），也就是不是不由父组件引发，那么<code>getDerivedStateFromProps</code>也不会被调用，如自身<code>setState</code>引发或者<code>forceUpdate</code>引发</p>
</blockquote>
<p><strong>React v16.3 的生命周期图</strong></p>
<p><img src="https://poetries1.gitee.io/img-repo/2019/10/419.png" alt></p>
<blockquote>
<p>这样的话理解起来有点乱，在<code>React v16.4</code>中改正了这一点，让<code>getDerivedStateFromProps</code>无论是<code>Mounting</code>还是<code>Updating</code>，也无论是因为什么引起的<code>Updating</code>，全部都会被调用，具体可看<code>React v16.4</code>的生命周期图</p>
</blockquote>
<p><strong>React v16.4后的getDerivedStateFromProps</strong></p>
<blockquote>
<p><code>static getDerivedStateFromProps(props, state)</code> 在组件创建时和更新时的render方法之前调用，它应该返回一个对象来更新状态，或者返回<code>null</code>来不更新任何内容</p>
</blockquote>
<h4 id="2-2-2-getSnapshotBeforeUpdate"><a href="#2-2-2-getSnapshotBeforeUpdate" class="headerlink" title="2.2.2 getSnapshotBeforeUpdate"></a>2.2.2 getSnapshotBeforeUpdate</h4><blockquote>
<p><code>getSnapshotBeforeUpdate()</code> 被调用于<code>render</code>之后，可以读取但无法使用DOM的时候。它使您的组件可以在可能更改之前从DOM捕获一些信息（例如滚动位置）。此生命周期返回的任何值都将作为参数传递给<code>componentDidUpdate（）</code></p>
</blockquote>
<p>官网给的例子</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ScrollingList</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>(props) &#123;</span><br><span class="line">    <span class="keyword">super</span>(props);</span><br><span class="line">    <span class="keyword">this</span>.listRef = React.createRef();</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  getSnapshotBeforeUpdate(prevProps, prevState) &#123;</span><br><span class="line">    <span class="comment">//我们是否要添加新的 items 到列表?</span></span><br><span class="line">    <span class="comment">// 捕捉滚动位置，以便我们可以稍后调整滚动.</span></span><br><span class="line">    <span class="keyword">if</span> (prevProps.list.length &lt; <span class="keyword">this</span>.props.list.length) &#123;</span><br><span class="line">      <span class="keyword">const</span> list = <span class="keyword">this</span>.listRef.current;</span><br><span class="line">      <span class="keyword">return</span> list.scrollHeight - list.scrollTop;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  componentDidUpdate(prevProps, prevState, snapshot) &#123;</span><br><span class="line">    <span class="comment">//如果我们有snapshot值, 我们已经添加了 新的items.</span></span><br><span class="line">    <span class="comment">// 调整滚动以至于这些新的items 不会将旧items推出视图。</span></span><br><span class="line">    <span class="comment">// (这边的snapshot是 getSnapshotBeforeUpdate方法的返回值)</span></span><br><span class="line">    <span class="keyword">if</span> (snapshot !== <span class="literal">null</span>) &#123;</span><br><span class="line">      <span class="keyword">const</span> list = <span class="keyword">this</span>.listRef.current;</span><br><span class="line">      list.scrollTop = list.scrollHeight - snapshot;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  render() &#123;</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">      &lt;div ref=&#123;<span class="keyword">this</span>.listRef&#125;&gt;&#123;<span class="comment">/* ...contents... */</span>&#125;&lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">    );</span></span><br><span class="line"><span class="regexp">  &#125;</span></span><br><span class="line"><span class="regexp">&#125;</span></span><br></pre></td></tr></table></figure>
<h2 id="三、参考"><a href="#三、参考" class="headerlink" title="三、参考"></a>三、参考</h2><ul>
<li><a href="https://zhuanlan.zhihu.com/p/38030418" target="_blank" rel="noopener">React v16.3之后的组件生命周期函数</a></li>
</ul>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2018/11/18/react-performance-optimization/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2018/11/19/pm2-summary/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
